package org.raymond.iworks.study.netty.atguigu.netty.groupchat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author raymond
 * @version V1.0
 * @Description: TODO
 */
@Slf4j
public class GroupChatServerHandler extends SimpleChannelInboundHandler<String> {
    private static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    // channel建立连接
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        log.info("{} handlerAdded", ctx.name());
        // 通过channels通知所有在线的客户端,不需要自己去遍历
        channels.writeAndFlush(String.format("%s 加入聊天群.", ctx.channel().remoteAddress()));
        channels.add(ctx.channel());
    }

    // channel断开连接
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        log.info("{} handlerRemoved", ctx.name());
        channels.writeAndFlush(String.format("%s 退出群.", ctx.channel().remoteAddress()));
        log.info("{}", channels.size());
    }

    // chanel处于活动状态
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("{} channelActive", ctx.name());
        log.info("{} 上线了", ctx.channel().remoteAddress());
    }

    // channel处于非活动状态
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("{} channelInactive", ctx.name());
        log.info("{} 离线", ctx.channel().remoteAddress());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        log.info("{} channelRead0", ctx.name());
        Channel self = ctx.channel();
        channels.forEach(other->{
            if(other!=self){
                other.writeAndFlush(String.format(" %s->%s", self.remoteAddress(), msg));
            }else{
                self.writeAndFlush(String.format(" 我发出的消息->%s", msg));
            }
        });
    }
}
